package edu.yuhf.web.filter;

import edu.yuhf.domain.Permission;
import edu.yuhf.domain.User;
import edu.yuhf.service.PermissionServiceImpl;
import edu.yuhf.service.iface.PermissionService;
import lombok.extern.log4j.Log4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter(dispatcherTypes = {
        DispatcherType.FORWARD
}, urlPatterns = { "/views/*" })
@Log4j
public class UserPermissionCheckFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        PermissionService permissionService=new PermissionServiceImpl();
        HttpServletRequest request=(HttpServletRequest)req;
        HttpSession session=request.getSession();
        User user=(User)session.getAttribute("user");
        List<Permission> list=permissionService.getPermissionByUserId(user.getId());
        session.setAttribute("permissions",list);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
